import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, logout, getUserInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken())
  const userInfo = ref(null)
  const permissions = ref([])
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.real_name || '')
  const userRole = computed(() => userInfo.value?.role || '')
  
  // 登录
  const loginAction = async (loginForm) => {
    try {
      const response = await login({
        identifier: loginForm.username,
        password: loginForm.password
      })
      
      if (response.success && response.data) {
        const { tokens, user } = response.data
        
        token.value = tokens.accessToken
        userInfo.value = user
        permissions.value = user.permissions || []
        
        setToken(tokens.accessToken)
        
        return Promise.resolve()
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      return Promise.reject(error)
    }
  }
  
  // 退出登录
  const logoutAction = async () => {
    try {
      // 只有在有token的情况下才调用后端logout API
      if (token.value) {
        await logout()
      }
    } catch (error) {
      // 即使后端logout失败，也要清除本地数据
      console.warn('后端退出登录失败，但仍会清除本地数据:', error)
    } finally {
      // 无论API调用是否成功，都要清除本地数据
      token.value = ''
      userInfo.value = null
      permissions.value = []
      removeToken()
      
      // 清除其他可能的本地存储
      localStorage.clear()
      sessionStorage.clear()
    }
  }
  
  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      if (!token.value) {
        throw new Error('未登录')
      }
      
      const response = await getUserInfo()
      
      if (response.data) {
        userInfo.value = response.data
        permissions.value = response.data.permissions || []
        
        return Promise.resolve(response.data)
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      // 如果获取用户信息失败，清除token
      token.value = ''
      userInfo.value = null
      permissions.value = []
      removeToken()
      
      return Promise.reject(error)
    }
  }
  
  // 检查认证状态
  const checkAuth = async () => {
    if (token.value && !userInfo.value) {
      try {
        await getUserInfoAction()
      } catch (error) {
        console.error('检查认证状态失败:', error)
      }
    }
  }
  
  // 检查权限
  const hasPermission = (permission) => {
    if (!permission) return true
    return permissions.value.includes(permission)
  }
  
  // 检查角色
  const hasRole = (role) => {
    if (!role) return true
    return userRole.value === role
  }
  
  return {
    // 状态
    token,
    userInfo,
    permissions,
    
    // 计算属性
    isLoggedIn,
    userName,
    userRole,
    
    // 方法
    login,
    loginAction,
    logoutAction,
    getUserInfoAction,
    checkAuth,
    hasPermission,
    hasRole
  }
})